2D Animated Orbits
Learn how to plot 2D animated orbits.
Now, let’s animate the orbit. Note that you have reset the argument of perigee to be 0 degrees.
Matplotlib’s FuncAnimation() takes a function and computes the next value given a range, plots the new value, waits a specified period of time, and then plots the next value. In your case, your animation is really just displaying the pre-computed X and Y coordinates of the orbit. You need to do some prep work to plot the orbit, plot the starting point of a red dot that will go around the orbit, and internally define an animate() function that accepts the incremental value i and returns (pos[i][1], pos[i][0]), so that the FuncAnimation() function can plot the new coordinates. Since pos[i] will give you the entire list of X or Y coordinates, you use the second [1] to get the X coordinates or [0] to get the Y coordinates of the nested list.
The comma is important after red_dot; the comma means that red_dot is treated as a tuple and not just as a list of lists. FuncAnimation takes a lot of arguments:
-
Figis the plot so the animation knows where to display the animation -
Animateis the function that provides the animation -
Framesis the source of data (the incrementalimentioned earlier) that provides the animation. In this case, since you are iterating through an array, you want a range, as large as the original time array, that providesintsso that the animation can iterate through each element of the array -
Intervalis the time delay between each iteration of the animation -
Blittingis a 2D graphics technique that separates the background of the plot from the moving red dot. If this argument isTrue, the background is frozen in place, and only the red dot is re-animated each time. It should make the animation load and run faster because it is only re-computing the red dot’s coordinates, not re-displaying the entire screen -
Repeatasks if the animation should play once and freeze, or continue indefinitely. There is also an optionalrepeat_delayparameter that can delay the repeat by the specified number of seconds There are a few other optional arguments that you did not use [2]. Finally, you will finish up with the plotting cleanup and running the code.
plt.plot(0, 0, 'bo', markersize=9, label="Earth")
plt.tick_params(
axis='both', # changes apply to both axes
which='both', # both major and minor ticks are affected
bottom=False, # ticks along the bottom edge are off
top=False, # ticks along the top edge are off
labelbottom=False, # labels along the bottom edge are off
left=False,
labelleft=False)
plt.legend(loc="upper right")
plt.title('Orbital Simulation')
plt.show()
Let’s see what you have created. This will be a static screenshot of the animated orbit.
Here is the actual GIF; you will get to saving GIFs later!